Popular Searches
Popular Course Categories
Popular Courses

Mapping HTTP Requests Using Request Mapping Annotations

Mapping HTTP Requests Using Request Mapping Annotations

Spring MVC and Enterprise Web Development

Mapping HTTP Requests Using Request Mapping Annotations

Course: Advanced Java Training

Topic: Mapping HTTP Requests Using Request Mapping Annotations

Course Link: Advanced Java Training at JustAcademy

Demo Link: Register for a Course Demo

Website: JustAcademy Official Website


1. Introduction to HTTP Request Mapping

HTTP request mapping is a fundamental feature of Spring MVC that connects incoming HTTP requests to specific controller methods. It enables developers to define which method should execute when a client accesses a URL using a particular HTTP method, request parameter, header, or media type.

Spring MVC provides annotations such as @RequestMapping, @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, and @PatchMapping to simplify request handling.

For example, an online shopping application may use request mappings to display products, create orders, update customer information, and delete unwanted records.

Learning Objectives

  • Understand HTTP request mapping in Spring MVC.
  • Learn the purpose of the @RequestMapping annotation.
  • Understand HTTP-specific mapping annotations.
  • Configure class-level and method-level mappings.
  • Capture URL values using @PathVariable.
  • Read query parameters using @RequestParam.
  • Map requests using headers, parameters, and media types.
  • Build and test a controller with multiple endpoints.

2. What Is Request Mapping in Spring MVC?

Request mapping is the mechanism through which Spring identifies the controller method responsible for handling an incoming HTTP request. The mapping rules can include a URL path, HTTP method, request parameters, headers, and supported content types.

When a request arrives, the DispatcherServlet coordinates request processing. Spring examines registered handler mappings to identify a matching controller method and then invokes that method through the appropriate HandlerAdapter.

Example

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

    @GetMapping("/home")
    public String showHomePage() {
        return "home";
    }
}

In this example, a GET request to /home invokes the showHomePage() method. The method returns the logical view name home, which Spring resolves using the configured view technology.

3. Understanding the @RequestMapping Annotation

The @RequestMapping annotation is used to map HTTP requests to controller classes or methods. It supports several conditions, including URL paths, HTTP methods, request parameters, headers, and media types.

It can be declared at the class level to define a common URL prefix and at the method level to define a specific endpoint.

Basic Syntax

@RequestMapping(
    value = "/products",
    method = RequestMethod.GET
)
public String getProducts() {
    return "products";
}

Important Attributes

Attribute Purpose Example
value Defines one or more URL paths. value = "/products"
path Defines one or more URL paths; an alias for value. path = "/products"
method Restricts the mapping to specified HTTP methods. method = RequestMethod.GET
params Matches specified request parameter conditions. params = "category=books"
headers Matches specified request header conditions. headers = "X-Source=web"
consumes Restricts the request Content-Type. consumes = "application/json"
produces Restricts the response media types the handler can produce. produces = "application/json"
name Assigns a logical name to a mapping. name = "productList"

4. Class-Level and Method-Level Request Mapping

Spring MVC supports combining class-level and method-level mappings to organize related endpoints under a common path.

Example

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/employees")
public class EmployeeController {

    @GetMapping
    public String listEmployees() {
        return "employees";
    }

    @GetMapping("/details")
    public String employeeDetails() {
        return "employee-details";
    }
}

Explanation:

  • The class-level mapping defines the common prefix /employees.
  • The first method handles GET requests to /employees.
  • The second method handles GET requests to /employees/details.
  • This structure groups related endpoints inside one controller.

5. HTTP-Specific Request Mapping Annotations

Spring MVC provides specialized mapping annotations for commonly used HTTP methods. These annotations make controller code clearer and help specify the intended operation for each endpoint.

Annotation HTTP Method Common Purpose
@GetMapping GET Retrieve information.
@PostMapping POST Create a resource or submit data for processing.
@PutMapping PUT Replace or update a resource representation.
@PatchMapping PATCH Apply a partial resource update.
@DeleteMapping DELETE Delete a resource.
@RequestMapping Configurable Map requests using one or more supported conditions.

5.1 Using @GetMapping

The @GetMapping annotation maps HTTP GET requests. It is commonly used to retrieve information or display a page.

@GetMapping("/students")
public String showStudents() {
    return "students";
}

A browser request to GET /students invokes the method and returns the logical view name students.

5.2 Using @PostMapping

The @PostMapping annotation maps HTTP POST requests. It is commonly used to submit forms or create resources.

@PostMapping("/students")
public String addStudent() {
    return "student-success";
}

In a complete application, this method would normally receive and validate submitted data before calling a service to create the student.

5.3 Using @PutMapping

The @PutMapping annotation maps HTTP PUT requests. PUT is generally used to replace a resource representation at a known URI.

@PutMapping("/students/{id}")
public String updateStudent(@PathVariable Long id) {
    return "student-updated";
}

The id value is extracted from the URL. A real implementation would use it to locate the student and process the update.

5.4 Using @PatchMapping

The @PatchMapping annotation maps HTTP PATCH requests, which are commonly used for partial updates.

@PatchMapping("/students/{id}/email")
public String updateStudentEmail(
        @PathVariable Long id) {
    return "email-updated";
}

This endpoint could be extended to receive a new email address and update only that field. The example demonstrates mapping, not a complete update implementation.

5.5 Using @DeleteMapping

The @DeleteMapping annotation maps HTTP DELETE requests. It is typically used to remove a resource.

@DeleteMapping("/students/{id}")
public String deleteStudent(@PathVariable Long id) {
    return "student-deleted";
}

In a REST API, deletion endpoints often return an appropriate status code such as 204 No Content when deletion succeeds and no response body is needed.

6. Using @PathVariable to Capture URL Values

The @PathVariable annotation binds a value from a URI path segment to a controller method parameter. It is especially useful when a URL identifies a specific resource.

Example

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@Controller
public class ProductController {

    @GetMapping("/products/{id}")
    public String showProduct(
            @PathVariable("id") Long id,
            Model model) {

        model.addAttribute("productId", id);
        return "product-details";
    }
}

For a request to /products/25, Spring binds the path segment 25 to the id parameter.

Multiple Path Variables

@GetMapping("/departments/{departmentId}/employees/{employeeId}")
public String showEmployee(
        @PathVariable Long departmentId,
        @PathVariable Long employeeId) {

    return "employee-details";
}

For /departments/3/employees/42, the method receives department ID 3 and employee ID 42.

7. Using @RequestParam to Read Query Parameters

The @RequestParam annotation binds query parameters or form parameters to method arguments. It is useful for searching, filtering, pagination, and reading submitted form values.

Example

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class SearchController {

    @GetMapping("/search")
    public String search(
            @RequestParam("keyword") String keyword,
            Model model) {

        model.addAttribute("keyword", keyword);
        return "search-results";
    }
}

When the client requests /search?keyword=Java, Spring binds Java to the keyword parameter.

Optional Parameters and Default Values

@GetMapping("/products")
public String filterProducts(
        @RequestParam(defaultValue = "all") String category,
        @RequestParam(defaultValue = "1") int page,
        Model model) {

    model.addAttribute("category", category);
    model.addAttribute("page", page);
    return "products";
}

If the request does not include category or page, Spring uses the specified default values.

8. Mapping Requests Based on Parameters

The params attribute restricts a mapping according to the presence, absence, or value of request parameters.

Example

@GetMapping(value = "/reports", params = "type=sales")
public String salesReport() {
    return "sales-report";
}

@GetMapping(value = "/reports", params = "type=inventory")
public String inventoryReport() {
    return "inventory-report";
}

Requests with ?type=sales match the sales handler, while requests with ?type=inventory match the inventory handler.

Parameter Matching Options

Condition Meaning
params = "active" The active parameter must be present.
params = "!active" The active parameter must be absent.
params = "type=books" The type parameter must have the value books.
params = "type!=books" The type parameter must not have the value books.

9. Mapping Requests Based on Headers

HTTP headers provide metadata about a request, such as the content type, accepted response formats, authorization information, and custom application values.

The headers attribute allows a mapping to require specific header conditions.

Example

@GetMapping(value = "/dashboard", headers = "X-Client=web")
public String webDashboard() {
    return "web-dashboard";
}

This handler matches requests to /dashboard that include the header X-Client: web.

For matching content types and accepted response types, the consumes and produces attributes are generally clearer than using raw header conditions.

10. Using consumes to Match Request Content Types

The consumes attribute specifies the media types a handler accepts. It is useful when an endpoint expects JSON, XML, or form data.

Example

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ApiController {

    @PostMapping(
        value = "/api/students",
        consumes = MediaType.APPLICATION_JSON_VALUE
    )
    public String createStudent(@RequestBody Student student) {
        return "Student received: " + student.getName();
    }
}

This endpoint accepts JSON requests when the request has a compatible Content-Type header, such as application/json. The request body is converted to a Student object using an appropriate message converter.

11. Using produces to Specify Response Media Types

The produces attribute restricts the media types a handler can return. Spring considers this condition alongside request information, including the client's Accept header.

Example

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class StudentApiController {

    @GetMapping(
        value = "/api/message",
        produces = MediaType.APPLICATION_JSON_VALUE
    )
    public Message getMessage() {
        return new Message("Welcome to Spring MVC");
    }
}

In this example, the endpoint is intended to return a JSON representation of the Message object. The application must have a suitable HTTP message converter configured.

Note: The Message class must be defined separately with an appropriate property and getter, or as a suitable Java record.

12. Combining Multiple Mapping Conditions

Spring MVC allows several mapping conditions to be combined to create more specific endpoints. A request must satisfy all declared conditions for the handler to match.

Example

@GetMapping(
    value = "/products",
    params = "category=electronics",
    headers = "X-Client=web",
    produces = "application/json"
)
public List<Product> getElectronics() {
    return productService.findElectronics();
}

This example assumes that Product, productService, and the required imports are defined. The mapping requires the matching URL, the specified query parameter, the custom header, and a compatible accepted response media type.

13. Using RequestMapping with REST Controllers

Request mapping annotations are widely used to create REST APIs. A REST controller typically returns data instead of a logical view name.

Example: REST API Controller

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/students")
public class StudentRestController {

    @GetMapping
    public String getAllStudents() {
        return "All students";
    }

    @GetMapping("/{id}")
    public String getStudent(@PathVariable Long id) {
        return "Student ID: " + id;
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public String createStudent() {
        return "Student created";
    }

    @PutMapping("/{id}")
    public String replaceStudent(@PathVariable Long id) {
        return "Student replaced: " + id;
    }

    @PatchMapping("/{id}")
    public String partiallyUpdateStudent(@PathVariable Long id) {
        return "Student partially updated: " + id;
    }

    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deleteStudent(@PathVariable Long id) {
        // Call the service layer to delete the student.
    }
}

This example illustrates endpoint mapping and status-code annotations. In a production API, methods should normally accept suitable request objects, delegate operations to a service, and return appropriate response data or status codes.

14. Request Mapping and HTTP Status Codes

HTTP status codes communicate the outcome of a request. Spring MVC allows applications to specify response status codes using annotations such as @ResponseStatus or by returning a ResponseEntity.

Status Code Meaning Common Usage
200 OK Request succeeded. Successful retrieval or update with a response body.
201 Created A resource was created. Successful resource creation.
204 No Content Request succeeded without a response body. Successful deletion or another operation with no content.
400 Bad Request Request data is invalid. Invalid parameters or malformed input.
404 Not Found Requested resource or endpoint was not found. Unknown resource or unmatched URL.
405 Method Not Allowed The URL does not support the requested HTTP method. Using POST on a GET-only endpoint.
500 Internal Server Error An unexpected server-side error occurred. Unhandled application failure.

15. Common Request Mapping Errors

Error Possible Cause Solution
404 Not Found Incorrect URL or missing controller mapping. Verify the URL, context path, component scanning, and mapping annotations.
405 Method Not Allowed HTTP method does not match the endpoint. Use the correct method, such as GET or POST.
400 Bad Request Invalid parameter or failed type conversion. Check parameter values and expected Java types.
Ambiguous mapping Multiple handler methods match the same request conditions. Make URL paths or mapping conditions distinct.
Missing request parameter A required parameter was not supplied. Supply the parameter or configure it as optional with a default value.
Media type mismatch Request Content-Type or Accept header does not match the mapping. Check the consumes and produces conditions.
Path variable conversion error The URL value cannot be converted to the declared parameter type. Use a valid value or handle conversion errors appropriately.

16. Best Practices for Request Mapping

  • Use HTTP-specific annotations such as @GetMapping and @PostMapping when possible.
  • Define a common URL prefix at the controller level when endpoints belong to the same resource group.
  • Use clear and consistent resource-oriented URL patterns.
  • Use @PathVariable for values that identify resources in the URL path.
  • Use @RequestParam for filtering, sorting, pagination, and query options.
  • Use consumes and produces when content-type constraints are important.
  • Avoid overlapping mappings that can create ambiguous handler selection.
  • Choose HTTP methods according to the intended operation.
  • Validate incoming data before executing business logic.
  • Return appropriate status codes and meaningful error responses.
  • Keep database operations and business rules in service and repository layers.
  • Test endpoints with MockMvc, integration tests, or an HTTP client.

17. Practical Exercise

Project: Employee Management Request Mapping

Create a Spring MVC controller that handles employee-related requests using different HTTP methods.

Requirements

  1. Create an Employee model with ID, name, and department fields.
  2. Define a controller-level mapping using /employees.
  3. Use @GetMapping to display all employees.
  4. Use @GetMapping("/{id}") to retrieve one employee by ID.
  5. Use @PostMapping to create an employee.
  6. Use @PutMapping("/{id}") to replace employee details.
  7. Use @PatchMapping("/{id}") to update selected employee fields.
  8. Use @DeleteMapping("/{id}") to delete an employee.
  9. Use @RequestParam to filter employees by department.
  10. Test successful requests and invalid URLs or HTTP methods.

Expected Learning Outcome

After completing the exercise, learners should be able to create REST-style endpoints, capture path variables, process query parameters, and select suitable request mapping annotations.

18. Interview Questions and Answers

Q1. What is request mapping in Spring MVC?

Answer: Request mapping connects incoming HTTP requests to controller methods using conditions such as URL path, HTTP method, request parameters, headers, and media types.

Q2. What is the purpose of @RequestMapping?

Answer: It defines request mapping conditions at the class or method level. It can map different HTTP methods and supports additional conditions.

Q3. What is the difference between @RequestMapping and @GetMapping?

Answer: @RequestMapping supports configurable HTTP methods and other mapping conditions. @GetMapping is a specialized annotation for HTTP GET requests.

Q4. What is the difference between @PathVariable and @RequestParam?

Answer: @PathVariable reads values from URI path segments, while @RequestParam reads request parameters, commonly from the query string or form data.

Q5. What is @PostMapping used for?

Answer: It maps HTTP POST requests, often used to submit data or create a resource.

Q6. What is the purpose of consumes?

Answer: The consumes attribute restricts the media types accepted by a handler, typically using the request's Content-Type.

Q7. What is the purpose of produces?

Answer: The produces attribute specifies the response media types a handler can produce and helps Spring match requests against the client's Accept header.

Q8. What is an ambiguous mapping error?

Answer: It occurs when Spring detects multiple handler methods that cannot be distinguished by their request mapping conditions.

Q9. Can multiple mapping conditions be used together?

Answer: Yes. A mapping can combine a URL path, HTTP method, request parameters, headers, and media-type conditions.

Q10. Why should controller methods use specific HTTP methods?

Answer: Specific HTTP methods make endpoint behavior clearer, improve API consistency, and reduce accidental handling of requests using inappropriate methods.

19. Quick Revision Checklist

  • @RequestMapping maps requests to controller classes or methods.
  • @GetMapping handles GET requests.
  • @PostMapping handles POST requests.
  • @PutMapping handles PUT requests.
  • @PatchMapping handles PATCH requests.
  • @DeleteMapping handles DELETE requests.
  • Class-level mappings define shared URL prefixes.
  • @PathVariable captures URL path values.
  • @RequestParam reads request parameters.
  • params and headers add mapping conditions.
  • consumes restricts accepted request media types.
  • produces restricts response media types.
  • Distinct mapping conditions help prevent ambiguous mappings.

20. Conclusion

Mapping HTTP requests using Spring MVC annotations is essential for building organized Java web applications and REST APIs. Annotations such as @RequestMapping, @GetMapping, @PostMapping, @PutMapping, @PatchMapping, and @DeleteMapping provide a clear way to connect URLs and HTTP methods to controller logic.

By combining request mappings with path variables, request parameters, header conditions, and media-type constraints, developers can build endpoints that are easier to understand, maintain, and test.

Explore the Advanced Java Training course at JustAcademy to learn more about Spring MVC and Java web development.

Visit the JustAcademy official website or register for a course demo to explore available training options.

Reference

For additional technical details, consult the official Spring Framework documentation on mapping requests.

Previous Next
whatsapp